/**
 * AddressCleaner - 地址清洗工具
 * 地址标准化、省市区提取
 */

class AddressCleaner {

    // 简单的省份匹配正则（用于提取）
    static PROVINCES_REGEX = /(.*?(?:省|自治区|市|特别行政区))/;

    /**
     * 清洗地址
     * @param {string} value 
     * @returns {string|null}
     */
    static clean(value) {
        if (!value) return null;
        let str = String(value).trim();

        // 移除特殊字符，连续空格转单一空格
        str = str.replace(/[\r\n\t]/g, ' ').replace(/\s+/g, ' ');

        if (str.length < 2) return null; // 太短的不算有效地址

        return str;
    }

    /**
     * 解析地址 (提取省市区)
     * 注意：这是基于正则的简单提取，复杂场景建议接入专门的NLP库或GIS服务
     * @param {string} value 
     */
    static parse(value) {
        const cleaned = this.clean(value);
        if (!cleaned) {
            return {
                valid: false,
                original: value,
                province: null,
                city: null,
                district: null,
                detail: null
            };
        }

        let province = null;
        let city = null;
        let district = null;
        let detail = cleaned;

        // 1. 提取省/直辖市
        // 匹配规则：2-5个字 + (省|自治区|市)
        // 注意："北京市" 既匹配 "市" 也在这层处理
        const provinceMatch = cleaned.match(/^(.{2,10}?(?:省|自治区|市|特别行政区))/);
        if (provinceMatch) {
            province = provinceMatch[1];
            detail = detail.substring(province.length);
        }

        // 2. 提取市/州/盟
        if (detail) {
            const cityMatch = detail.match(/^(.{2,10}?(?:市|州|盟|地区))/);
            if (cityMatch) {
                city = cityMatch[1];
                detail = detail.substring(city.length);
            }
        }

        // 3. 提取区/县
        if (detail) {
            const districtMatch = detail.match(/^(.{2,10}?(?:区|县|市|旗))/);
            if (districtMatch) {
                district = districtMatch[1];
                detail = detail.substring(district.length);
            }
        }

        return {
            valid: true,
            original: value,
            formatted: cleaned,
            province,
            city,
            district,
            detail: detail.trim() // 剩余部分作为详情
        };
    }

    /**
     * 验证是否有效地址
     */
    static isValid(value) {
        return this.clean(value) !== null;
    }
}

module.exports = AddressCleaner;
